package cn.steel.controller.buyer;

import cn.steel.domain.entity.User;
import cn.steel.domain.vo.CartVo;
import cn.steel.service.CartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/buyer/cart")
@Api(tags = "购物车管理接口")
@PreAuthorize("hasAuthority('BUYER')")
@RequiredArgsConstructor
public class CartController {

    private final CartService cartService;

    @ApiOperation("显示购物车页面")
    @GetMapping("/view")
    public String showCart(@SessionAttribute(value = "user", required = false) User user, Model model, RedirectAttributes redirectAttributes) {
        if (user == null || !"BUYER".equals(user.getRole())) {
            log.warn("用户未登录或非买家，尝试访问购物车");
            redirectAttributes.addFlashAttribute("error", "请以买家身份登录后操作");
            return "redirect:/login?url=/buyer/cart/view";
        }
        log.info("显示购物车页面: userId={}", user.getId());
        List<CartVo> carts = cartService.getCartByUserId(user.getId());
        model.addAttribute("carts", carts);
        return "buyer/cart";
    }

    @ApiOperation("更新购物车（表单提交）")
    @PostMapping("/update")
    public String updateCart(
            @SessionAttribute(value = "user", required = false) User user,
            @RequestParam Map<String, String> params,
            RedirectAttributes redirectAttributes) {
        if (user == null || !"BUYER".equals(user.getRole())) {
            log.warn("用户未登录或非买家，尝试更新购物车");
            redirectAttributes.addFlashAttribute("error", "请以买家身份登录后操作");
            return "redirect:/login?url=/buyer/cart/view";
        }
        log.info("更新购物车: userId={}, params={}", user.getId(), params);
        try {
            List<CartVo> carts = cartService.getCartByUserId(user.getId());
            for (CartVo cart : carts) {
                String quantityKey = "quantity_" + cart.getId();
                if (params.containsKey(quantityKey)) {
                    try {
                        int quantity = Integer.parseInt(params.get(quantityKey));
                        if (quantity > 0) {
                            cartService.updateCart(user.getId(), cart.getProductId(), quantity);
                        }
                    } catch (NumberFormatException e) {
                        log.warn("无效数量: key={}, value={}", quantityKey, params.get(quantityKey));
                    }
                }
                String selectedKey = "selected_" + cart.getId();
                boolean selected = params.containsKey(selectedKey) && "true".equals(params.get(selectedKey));
                cartService.updateCartSelection(user.getId(), cart.getProductId(), selected);
            }
            redirectAttributes.addFlashAttribute("success", true);
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        }
        return "redirect:/buyer/cart/view";
    }
    @ApiOperation("清空购物车")
    @PostMapping("/clear")
    public String clearCart(
            @SessionAttribute(value = "user", required = false) User user,
            RedirectAttributes redirectAttributes) {
        if (user == null || !"BUYER".equals(user.getRole())) {
            log.warn("用户未登录或非买家，尝试清空购物车");
            redirectAttributes.addFlashAttribute("error", "请以买家身份登录后操作");
            return "redirect:/login?url=/buyer/cart/view";
        }
        log.info("清空购物车: userId={}", user.getId());
        try {
            cartService.clearCart(user.getId());
            redirectAttributes.addFlashAttribute("success", true);
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        }
        return "redirect:/buyer/cart/view";
    }

    @ApiOperation("删除选中的购物车商品")
    @PostMapping("/delete-selected")
    public String deleteSelectedCarts(
            @SessionAttribute(value = "user", required = false) User user,
            @RequestParam Map<String, String> params,
            RedirectAttributes redirectAttributes) {
        if (user == null || !"BUYER".equals(user.getRole())) {
            log.warn("用户未登录或非买家，尝试删除选中的购物车商品");
            redirectAttributes.addFlashAttribute("error", "请以买家身份登录后操作");
            return "redirect:/login?url=/buyer/cart/view";
        }
        log.info("删除选中的购物车商品: userId={}", user.getId());
        try {
            // 先更新选中状态
            List<CartVo> carts = cartService.getCartByUserId(user.getId());
            for (CartVo cart : carts) {
                String selectedKey = "selected_" + cart.getId();
                boolean selected = params.containsKey(selectedKey) && "true".equals(params.get(selectedKey));
                cartService.updateCartSelection(user.getId(), cart.getProductId(), selected);
            }
            cartService.deleteSelectedCarts(user.getId());
            redirectAttributes.addFlashAttribute("success", true);
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        }
        return "redirect:/buyer/cart/view";
    }
}